package com.ziq.zcamp.bean.post

import android.graphics.Color
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.viewpager2.widget.ViewPager2
import com.donkingliang.groupedadapter.holder.BaseViewHolder
import com.facebook.imagepipeline.request.ImageRequest
import com.zhpan.bannerview.BannerViewPager
import com.zhpan.bannerview.BaseBannerAdapter
import com.ziq.base.extension.click
import com.ziq.zcamp.R
import com.ziq.zcamp.api.service.getFinalUrl
import com.ziq.zcamp.bean.common.BannerResult
import com.ziq.zcamp.bean.place.DetailGroup
import com.ziq.zcamp.community.CommunityPostingAdapter
import com.ziq.zcamp.databinding.ItemCommunityBannerBinding
import com.ziq.zcamp.databinding.ItemCommunityRecommendedBinding
import com.ziq.zcamp.extension.pageClick
import com.ziq.zcamp.login.ActionAfterLogin
import com.ziq.zcamp.login.LoginActivity
import com.ziq.zcamp.manager.GlobalContextManager
import com.ziq.zcamp.manager.PrivacyManager
import com.ziq.zcamp.manager.UserManager
import com.ziq.zcamp.util.ImageUtil
import com.ziq.zcamp.util.PictureUtil
import com.ziq.zcamp.view.SafetySimpleDraweeView
import net.lucode.hackware.magicindicator.buildins.UIUtil

class CommunityPostingGroup(val adapter: CommunityPostingAdapter) : DetailGroup() {

    override fun getHeaderViewType(groupPosition: Int): Int {
        return 0
    }

    override fun getChildViewType(groupPosition: Int, childPosition: Int): Int {
        if(childPosition == (0 + offset) && bannerList?.isNotEmpty() == true){
            return CommunityPostingAdapter.TYPE_BANNER
        } else {
            return CommunityPostingAdapter.TYPE_POSTING
        }
    }

    fun getPostingRealPosition(childPosition: Int):Int{
        if(bannerList?.isNotEmpty() == true && childPosition > (0 + offset)){
            return childPosition - 1
        }
        return childPosition
    }

    var postingList : List<PostingDetail>? = null
    private var bannerList : List<BannerResult.BannerItem>? = null
    private var bannerPosition = 0
    private var resetData = false
    var lastBanner: BannerViewPager<*>? = null

    //设置偏移量，如果显示露营人生的入口则偏移量为0，反之为1
    private var offset = 1

    fun hasShowCampLife(show : Boolean){
        offset = if (show) {
            0
        }else{
            1
        }
    }

    fun setBannerData(list : List<BannerResult.BannerItem>?){
        this.bannerList = list
        bannerPosition = 0
        resetData = true
    }

    override fun getChildrenCount(): Int {
        if(postingList?.isNotEmpty() == true && bannerList?.isNotEmpty() == true){
            return (postingList?.size?:0) + 1
        }
        return postingList?.size?:0
    }

    override fun hasHeader(groupPosition: Int): Boolean {
        return false
    }

    override fun hasFooter(groupPosition: Int): Boolean {
        return false
    }

    override fun onBindHeaderViewHolder(
        holder: BaseViewHolder?,
        groupPosition: Int
    ) {
    }

    override fun onBindFooterViewHolder(
        holder: BaseViewHolder?,
        groupPosition: Int
    ) {
    }

    override fun onBindChildViewHolder(
        holder: BaseViewHolder?,
        groupPosition: Int,
        childPosition: Int
    ) {
        val viewType = getChildViewType(groupPosition, childPosition)
        when (viewType) {
            CommunityPostingAdapter.TYPE_POSTING -> {
                onBindPosting(holder, groupPosition, childPosition)
            }
            CommunityPostingAdapter.TYPE_BANNER -> {
                onBindBanner(holder, groupPosition, childPosition)
            }
        }
    }

    private fun onBindBanner(
        holder: BaseViewHolder?,
        groupPosition: Int,
        childPosition: Int
    ){
        holder?.let {
            val binding = ItemCommunityBannerBinding.bind(holder.itemView)

            binding.banner.setAdapter(ImageAdapter())
            binding.banner.setAutoPlay(true)
            binding.banner.setInterval(3000)
            binding.banner.setCanLoop(true)
            binding.banner.setOffScreenPageLimit(3)
            binding.banner.setIndicatorSliderWidth(UIUtil.dip2px(binding.banner.context, 6.0))
            binding.banner.setIndicatorSliderGap(UIUtil.dip2px(binding.banner.context, 8.0))
            binding.banner.setIndicatorSliderColor(Color.argb(33, 32, 33, 31), Color.parseColor("#20211F"))

            binding.banner.pageClick { clickedView, position ->
                if(bannerList?.isNotEmpty() == true){
                    GlobalContextManager.getCurrentActivity()?.let {
                        PrivacyManager.checkPrivacy(it, action = {
                            val item = bannerList?.get(position)
//                            if(item?.jump_url?.startsWith("http", ignoreCase = true) == true){
//                                WebActivity.openWebView(GlobalContextManager.appContext!!, item?.jump_url?:"", "")
//                            }else {
//                                RouterCenter.parseLinkToDestination(GlobalContextManager.appContext, item?.jump_url?:"", "")
//                            }
                        })
                    }
                }
            }
            binding.banner.registerOnPageChangeCallback(null)
            binding.banner.create(bannerList)
            binding.banner.setCurrentItem(bannerPosition, false)
            binding.banner.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    super.onPageSelected(position)
                    bannerPosition = position
                }
            })
            if(adapter.isStop){
                binding.banner.stopLoop()
            } else {
                binding.banner.startLoop()
            }
            lastBanner = binding.banner
            if(resetData){
            }
        }
        resetData = false
    }

    class ImageAdapter : BaseBannerAdapter<BannerResult.BannerItem>() {

        override fun getLayoutId(viewType: Int): Int {
            return R.layout.item_image_banner_crop
        }

        override fun bindData(
            holder: com.zhpan.bannerview.BaseViewHolder<BannerResult.BannerItem>,
            data: BannerResult.BannerItem,
            position: Int,
            pageSize: Int
        ) {
            holder.findViewById<SafetySimpleDraweeView>(R.id.image).setImageURI(getFinalUrl(data.images?.getOrNull(0)?.url?:""))
        }

    }


    private fun onBindPosting(
        holder: BaseViewHolder?,
        groupPosition: Int,
        childPosition: Int
    ){
        val position = getPostingRealPosition(childPosition)
        val item = postingList?.get(position)
        if(item != null){
            holder?.let {
                val binding = ItemCommunityRecommendedBinding.bind(it.itemView)

                if(item.post?.p_type == 2){
                    binding.ivPostTypeLabel.visibility = View.VISIBLE
                    binding.ivPostTypeLabel.setImageResource(R.drawable.icon_post_video_label)
                } else {
                    binding.ivPostTypeLabel.visibility = View.GONE
                }

                holder.itemView.click {
                    adapter.postingAdapterAction?.itemClick(item)
                }

                binding.llUserInfo.click {
                    adapter.postingAdapterAction?.userInfoClick(item)
                }

                var content = ""
                if(item.post?.title?.isNotEmpty() == true){
                    content = "${item.post?.title}"
                }else if(item.post?.content?.isNotEmpty() == true){
                    content = "${item.post?.content}"
                }
                if (content.isEmpty()){
                    binding.title.visibility = View.GONE
                    val paddingtop = GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_12)
                    val lp = binding.avator.layoutParams as LinearLayout.LayoutParams
                    lp.topMargin = paddingtop
                    lp.bottomMargin = paddingtop
                    binding.avator.layoutParams = lp
                } else {
                    binding.title.visibility = View.VISIBLE
                    val paddingtop = GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_8)
                    val lp = binding.avator.layoutParams as LinearLayout.LayoutParams
                    lp.topMargin = paddingtop
                    lp.bottomMargin = paddingtop
                    binding.avator.layoutParams = lp
                }

                binding.title.text = content
                binding.name.text = "${item.user?.nick_name}"
                ImageUtil.updateImageFromNetwork(binding.avator, item.user?.header_url, ImageRequest.CacheChoice.DEFAULT)

                val imageInfo = item.post?.images?.getOrNull(0)
                if(imageInfo != null){
                    val params = binding.image.layoutParams as ViewGroup.LayoutParams
                    params.width = adapter.itemWidth
                    params.height = PictureUtil.calculatePictureViewHeight(adapter.itemWidth, imageInfo.width, imageInfo.height)
                    binding.image.layoutParams = params

                    ImageUtil.updateImageFromNetwork(binding.image, imageInfo.url, ImageRequest.CacheChoice.DEFAULT)

                } else {
                    val params = binding.image.layoutParams as ViewGroup.LayoutParams
                    params.width = adapter.itemWidth
                    params.height = adapter.itemWidth
                    binding.image.layoutParams = params
                }


                updateLikeUI(true, item, binding)

                binding.llCommentActionPraise.click {
                    LoginActivity.checkLogin( object : ActionAfterLogin {
                        override fun action() {
                            //点赞 帖子
                            if(binding.llCommentActionPraise.isSelected){
                                updateItemDataForUnLike(item, binding)
                                UserManager.instance.unlikePosting(item.post?.post_id?:"", item.user?.uid?:0, item.post?.like_nums?:0,
                                    onFail = {
                                        updateItemDataForLike(item, binding)
                                    }
                                )
                            } else {
                                updateItemDataForLike(item, binding)
                                UserManager.instance.likePosting(item.post?.post_id?:"", item.user?.uid?:0, item.post?.like_nums?:0,
                                    onFail = {
                                        updateItemDataForUnLike(item, binding)
                                    }
                                )
                            }
                        }
                    })
                }
            }
        }
    }

    fun updateItemDataForLike(item: PostingDetail, binding: ItemCommunityRecommendedBinding){
        item.post?.let {
            val likeNum = it.like_nums?:0
            it.like_nums = likeNum + 1
            it.is_like = true
        }
        updateLikeUI(false,item, binding)
    }

    fun updateItemDataForUnLike(item: PostingDetail, binding: ItemCommunityRecommendedBinding){
        item.post?.let {
            val likeNum = it.like_nums?:0
            if(likeNum > 0 ){
                it.like_nums = likeNum - 1
            }
            it.is_like = false
        }
        updateLikeUI(false, item, binding)
    }

    fun updateLikeUI(considerManager: Boolean, item: PostingDetail, binding: ItemCommunityRecommendedBinding){
        var likeNum = item.post?.like_nums?:0
        if(considerManager && item.post?.post_id?.isNotEmpty() == true && UserManager.instance.postingLike.value?.contains(item.post?.post_id) == true){
            binding.llCommentActionPraise.isSelected = UserManager.instance.postingLike.value!![item.post!!.post_id]!!.isLike
            likeNum = UserManager.instance.postingLike.value!![item.post!!.post_id]!!.num
            item.post?.like_nums = likeNum
        } else {
            binding.llCommentActionPraise.isSelected = item.post?.is_like?:false
        }
        binding.tvCommentActionPraiseCount.visibility = View.VISIBLE
        if(likeNum > 10000){
            binding.tvCommentActionPraiseCount.text = String.format("%.1f", (likeNum / 10000.0)) + GlobalContextManager.getString(
                R.string.wan)
        } else if(likeNum == 0){
            binding.tvCommentActionPraiseCount.text = ""
            binding.tvCommentActionPraiseCount.visibility = View.GONE
        }else {
            binding.tvCommentActionPraiseCount.text = likeNum.toString()
        }
    }



}